package com.atguigu.producer.demo.config;


import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.Nullable;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Configuration
public class RabbitConfig {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init(){
        //判断是否到达交换机
        rabbitTemplate.setConfirmCallback((@Nullable CorrelationData correlationData, boolean ack, @Nullable String cause)->{
            if(!ack){
                System.out.println("消息没有到达交换机,原因是"+cause);
            }else{
                System.out.println("消息到达了交换机啦le elelel");
            }
        });
        //判断是否到达队列,到达队列该方法不执行
        rabbitTemplate.setReturnCallback((Message message, int replyCode, String replyText, String exchange, String routingKey)->{
            log.warn("消息没有到达 {},路由键 {},错误消息为 {}",exchange,routingKey,new String(message.getBody()));
        });
    }

    @Bean
    public TopicExchange exchange(){
        return ExchangeBuilder.topicExchange("SPRING-TEST-EXCHANGE2").durable(true).build();
    }
    //业务队列
    @Bean
    public Queue queue(){
        Map<String,Object> map = new HashMap<>();
        map.put("x-dead-letter-exchange","SPRING-DEAD-EXCHANGE");
        map.put("x-dead-letter-routing-key","msg.dead");
        map.put("x-message-ttl", 10000);
        return QueueBuilder.durable("SPRING-TEST-QUEUE2").withArguments(map).build();
    }
    //业务交换机



    @Bean
    public Binding binding(TopicExchange exchange,Queue queue){
        return BindingBuilder.bind(queue).to(exchange).with("msg.a");
    }

    @Bean
    public TopicExchange deadExchange(){
        return ExchangeBuilder.topicExchange("SPRING-DEAD-EXCHANGE").durable(true).build();
    }

    @Bean
    public Queue deadQueue(){
        return QueueBuilder.durable("SPRING-DEAD-QUEUE").build();
    }

    @Bean
    public Binding deadBinding(TopicExchange deadExchange,Queue deadQueue){
        return BindingBuilder.bind(deadQueue).to(deadExchange).with("msg.dead");
    }
}
